package com.ny.zmb.openapi.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ny.zmb.openapi.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuhy
 * @description 聚合收银台下单接口
 * @date 2024/02/28
 */
public class AggCashierDemo {

    private static final String ALLCHAR = "0123456789ABCDEF";

    public static void main(String[] args) throws Exception {

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "order.createOrder");
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset","utf-8");
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        //银盛商户号
        reqMap.put("certId","826440345119153");//826440345119153测试环境可用商户号
        //reqMap.put("certId", "prdtest");
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
//        String publicFilePath = "D:/datas/test/service.cer";
        String publicFilePath = "D:/datas/prod/service.cer";
        byte[] byte1= RSA256Util.encrypt(publicFilePath, ByteUtil.hexStringToBytes(key));
        String encryptKeyCheck = Base64.encodeBase64String(byte1);
        reqMap.put("check", encryptKeyCheck);//加密后的密钥

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        bizContentMap.put("orderId", System.currentTimeMillis() + "00001");
        bizContentMap.put("msgCode","S3001");
        bizContentMap.put("mercId","826148551378003"); //测试使用
        //bizContentMap.put("mercId",""); //生产使用
        bizContentMap.put("busiCode","00490004");//测试使用
        //bizContentMap.put("busiCode","00510103"); //生产使用(聚合收银台)
        bizContentMap.put("shopDate",getCurrentDateTime("yyyyMMdd"));
        bizContentMap.put("amount",100);
        bizContentMap.put("paymentValidTime",30);
        bizContentMap.put("currency","CNY");
        bizContentMap.put("remark","模拟测试收银台支付订单备注");
        bizContentMap.put("note","模拟测试收银台支付订单说明");
        bizContentMap.put("backUrl","https://appdev.ysepay.com/openapiNotify/common/testNotify");
        bizContentMap.put("limitPay","1");
        bizContentMap.put("payMode","29");

        //商品明细
        Map<String, Object> detailMap = new HashMap<>();
        detailMap.put("costPrice",100);
        detailMap.put("receiptId","Ys001001");
        List<Map<String, String>> goodsDetails = new ArrayList<>();
        Map<String, String> goodsDetailsMap = new HashMap<>();
        goodsDetailsMap.put("goodsId","goodsId_test001");
        goodsDetailsMap.put("wxpayGoodsId","");
        goodsDetailsMap.put("goodsName","");
        goodsDetailsMap.put("quantity","1");
        goodsDetailsMap.put("price","100");
        goodsDetails.add(goodsDetailsMap);
        detailMap.put("goodsDetails", goodsDetails);
        bizContentMap.put("detail", detailMap);

        //商户门店编号
        bizContentMap.put("storeId","20240226001");

        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String privateFilePath = "D:/datas/cert/826440345119153/client.pfx";
        String privatePassword = "123456";
        String sign= RSA256Util.sign(sb1.toString(),privateFilePath,privatePassword);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String httpUrl = "https://appdev.ysepay.com/openapi/order/createOrder";
            String result = HttpRequestUtil.getDoPostResponse(httpUrl, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(publicFilePath,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            byte[] dataEncode=Base64.decodeBase64(resMap.get("businessData"));
            byte[] data= AESUtil.decrypt(dataEncode, ByteUtil.hexStringToBytes(key));
            String businessData=new String(data,"UTF-8");
            System.out.println("返回的业务参数为:"+businessData);
        } catch (Exception e) {
            e.printStackTrace();
            throw  e;
        }
    }

    /**
     * 格式化当前日期时间字符串
     * @return
     */
    private static  String getCurrentDateTime(String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }

}
